package com.lt.lumentracks.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lt.lumentracks.entity.po.PostTopic;
import com.lt.lumentracks.mapper.PostTopicMapper;
import com.lt.lumentracks.service.IPostTopicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 帖子话题表（关联表） 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-07-28
 */
@Service
public class PostTopicServiceImpl extends ServiceImpl<PostTopicMapper, PostTopic> implements IPostTopicService {

    // 更新帖子话题
    @Transactional
    @Override
    public void updatePostTopic(Integer postId, List<Integer> newTopicIdList) {
        if (newTopicIdList == null || newTopicIdList.isEmpty()) {
            return;
        }

        // 1.查询数据库，获取该帖子的话题列表
        QueryWrapper<PostTopic> qw_ptc = new QueryWrapper<PostTopic>().eq("post_id", postId);
        List<PostTopic> PostTopicList = this.list(qw_ptc);
        List<Integer> oldTopicIdList = PostTopicList.stream().map(PostTopic::getTopicId).toList();


        // 2.对比新旧话题集合
        // 找出要删除的话题集合（旧集合有，新集合没有，那就是要删除的）
        List<Integer> delTopicIdList = oldTopicIdList.stream()
                .filter(topicId -> !newTopicIdList.contains(topicId))
                .toList();

        // 找出要添加的话题集合（旧集合没有，新集合有，那就是要新增的）
        List<Integer> addTopicIdList = newTopicIdList.stream()
                .filter(topicId -> !oldTopicIdList.contains(topicId))
                .toList();

        // 两个集合里都有的话就是不变的，不用管


        // 3.执行数据库操作
        // 执行删除操作（删除要传入的是PostTopic的id列表，上面获取的是PostTopic的topicId列表，还要再做一次转换）
        if(!delTopicIdList.isEmpty()){
            List<Integer> delIdList = PostTopicList.stream()
                    .filter(pt -> delTopicIdList.contains(pt.getTopicId()))
                    .map(PostTopic::getId)
                    .toList();
            this.removeByIds(delIdList);
        }

        // 执行新增操作
        if(!addTopicIdList.isEmpty()){
            List<PostTopic> addPostTopicList = new ArrayList<>();
            for (Integer topicId : addTopicIdList) {
                PostTopic ptc = new PostTopic();
                ptc.setPostId(postId);
                ptc.setTopicId(topicId);
                addPostTopicList.add(ptc);
            }
            this.saveBatch(addPostTopicList);
        }
    }
}
